//
//  addressBook.m
//  SPToolDemo
//
//  Created by zhagnshupeng on 2017/11/9.
//  Copyright © 2017年 SP. All rights reserved.
//

#import "APPAddressBook.h"
#import <AddressBook/AddressBook.h>





@implementation APPAddressBook


- (void)allInfo {
    
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, nil);
   
    NSArray *array = (__bridge_transfer NSArray *)(ABAddressBookCopyArrayOfAllPeople(addressBook));
    NSMutableArray *peoples = @[].mutableCopy;
    for (NSInteger i = 0; i < array.count; i++) {
        
        ABRecordRef person = (__bridge ABRecordRef)(array[i]);
        
        NSString *firstNameLabel = (__bridge_transfer NSString *)(ABPersonCopyLocalizedPropertyName(kABPersonFirstNameProperty));
        NSString *firstName = (__bridge_transfer NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
        NSString *lastNameLabel =(__bridge_transfer NSString *)(ABPersonCopyLocalizedPropertyName(kABPersonLastNameProperty));
        NSString *lastName =(__bridge_transfer NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
        ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(person, kABPersonPhoneProperty);
        NSMutableArray *phones = @[].mutableCopy;
        for (int i=0; i<ABMultiValueGetCount(phoneMulti); i++) {
            
            NSString*phone= (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phoneMulti,i);
            NSString*label= (__bridge_transfer NSString *)ABMultiValueCopyLabelAtIndex(phoneMulti,i);
            [phones addObject:@{@"name":label,@"phone":phone}];
        }
        [peoples addObject:@{@"firstName":firstName,@"lastName":lastName,@"phones":phones}];
        
    }
    
    CFRelease(addressBook);
}

- (void) addressBookStatus{
    //1. 获取授权状态
    ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
    //2. 创建 AddrssBook
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
    //3. 没有授权时就授权
    if (status == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            //3.1 判断是否出错
            if (error) {
                return;
            }
            //3.2 判断是否授权
            if (granted) {
                NSLog(@"已经授权");
                CFRelease(addressBook);
            } else {
                NSLog(@"没有授权");
            }
        });
    }
    CFRelease(addressBook);
}
@end
